package com.juwei.round.irview;

import android.content.Context;
import android.hardware.ConsumerIrManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {
    private ConsumerIrManager consumerIrManager;
    private Boolean hasIR = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        Button btnLearn = findViewById(R.id.button2);
        btnLearn.setOnClickListener(view -> {
        });
        consumerIrManager = (ConsumerIrManager) getSystemService(Context.CONSUMER_IR_SERVICE);
        if (consumerIrManager != null && consumerIrManager.hasIrEmitter()) {
            hasIR = true;
            Toast.makeText(MainActivity.this, "OK: Found IR.", Toast.LENGTH_SHORT).show();
        } else {
            hasIR = false;
            Toast.makeText(MainActivity.this, "Error: Didn't find IR.", Toast.LENGTH_SHORT).show();
        }
        sendIR();
    }

    private void sendIR() {
        Button btnSend = findViewById(R.id.button1);
        btnSend.setOnClickListener(view -> {
            if (hasIR && consumerIrManager != null) {
                int frequency = 38000;
                int[] pattern = {3500, 3500, 500, 500, 500, 500};
                consumerIrManager.transmit(frequency, pattern);
            } else {
                Toast.makeText(MainActivity.this, "Fail: Didn't find IR.", Toast.LENGTH_SHORT).show();
            }
        });

    }
}